package org.example.config;

import org.springframework.beans.TypeMismatchException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.bind.support.WebExchangeBindException;
import org.springframework.web.server.ServerWebInputException;
import reactor.core.publisher.Mono;

import javax.validation.ConstraintViolationException;
import java.util.List;

/**
 * TODO 类功能介绍及重点或容易混淆点的说明。
 *
 * @version 1.0 2023/5/21 8:50 龙小南 新建类[说明]
 * @author: 龙小南
 * @Date: 2023/5/21 8:50
 * @Version 1.0[当前版本号]
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * body传参 JSR303 参数校验异常
     * @param ex
     * @return
     */
    @ExceptionHandler(org.springframework.web.bind.support.WebExchangeBindException.class)
    public Mono<String> handleExceptions(WebExchangeBindException ex){
        List<ObjectError> allErrors = ex.getBindingResult().getAllErrors();
        StringBuilder stringBuilder = new StringBuilder();
        for (ObjectError error : allErrors) {
            stringBuilder.append(error.getDefaultMessage()).append(";");
        }
        return Mono.just(stringBuilder.toString());
    }

    /** path 和 url序列化传参时 JSR303 抛出的异常 */
    @ExceptionHandler(ConstraintViolationException.class)
    public Mono<String> handleConstraintViolationException(ConstraintViolationException ex){
        return Mono.just(ex.getMessage());
    }

    @ExceptionHandler(ServerWebInputException.class)
    public Mono<String> handleServerWebInputException(ServerWebInputException ex){
        return Mono.just("参数输入异常");
    }



    @ExceptionHandler(Exception.class)
    public Mono<String> handleExceptions(Exception ex){
        return Mono.just(ex.getMessage());
    }

}
